#!/usr/bin/env python
#encoding:utf8
'''
Author: whb
e-mail:hbnnlong@163.com
Date:2016-04-21
'''

import email
import time
import traceback
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import smtplib
import conf

class SendMail():

    def __init__(self,to_addrs=[]):
        self._send_server = conf.MAIL.get("MAIL_SERVER")
        self.user,self.passwd = conf.MAIL.get("MAIL_SENDER"), conf.MAIL.get("MAIL_PASSWORD")
        self.to_addrs = to_addrs if to_addrs else conf.MAIL.get("TO_ADDRS")
        self._smtp = smtplib.SMTP_SSL(self._send_server,465)

    def send_email(self,subject="爬虫邮件",filename=None,msghtml=None,msgtxt=None):
        self.subject = subject
        ms = MIMEMultipart()
        Addrs = [email.utils.formataddr((False,addr)) for addr in self.to_addrs]
        ms['To'] = ','.join(Addrs)
        ms['From'] = self.user
        ms['Subject'] = self.subject
        ms['Date'] = email.utils.formatdate(time.time(),True)
        #ms.attach(MIMEText(self.txt))
        if msghtml:
            ms.attach(MIMEText(msghtml,'html','utf8'))

        if filename:
            attat = MIMEText(open(filename,'rb').read(),'base64','utf8')
            attat["Content-Type"]='application/octet-stream'
            attat['Content-Disposition']='attatcnment;filename="%s" ' % filename
            ms.attach(attat)

        if msgtxt:
            ms.attach(MIMEText(msgtxt,'plain','utf8'))
        self._smtp.login(self.user,self.passwd)
        try:
            self._smtp.sendmail(self.user,Addrs,ms.as_string())
            self._smtp.quit()
            return
        except Exception as e:
            traceback.print_exc()


if __name__=="__main__":
    S_mail = SendMail()
    S_mail.send_email(msghtml='test')
